import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import {aesEncrypt, aesDecrypt} from '../utils/security'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    userInfo: {
      id: null,
      email: '',
      nickname: '',
      isDisable: 0,
      token: ''
    },
    currentPage: '',
    downloadProgress: -1
  },
  mutations: {
    SET_USERINFO: (state, payload) => {
      state.userInfo = payload
      Object.keys(state.userInfo).forEach(tmpKey => {
        state.userInfo[tmpKey] = payload[tmpKey]
      })
    },
    LOG_OUT: (state, payload) => {
      state.userInfo = {
        id: null,
        email: '',
        nickname: '',
        isDisable: 0,
        token: ''
      }
    },
    UPDATE_PAGE_NAME: (state, payload) => {
      state.currentPage = payload + ''
    },
    UPDATE_DOWNLOAD_PROGRESS: (state, payload) => {
      state.downloadProgress = payload
    }
  },
  actions: {
    setUserInfo ({commit}, payload) {
      commit('SET_USERINFO', payload)
    },
    doLogout ({commit}, payload) {
      commit('LOG_OUT', payload)
    },
    updatePageName ({commit}, payload) {
      commit('UPDATE_PAGE_NAME', payload)
    },
    updateDownloadImgProgress ({commit}, payload) {
      commit('UPDATE_DOWNLOAD_PROGRESS', payload)
    }
  },
  getters: {
    isLogined: state => {
      if (state.userInfo.id != null &&
        state.userInfo.token != null &&
        state.userInfo.token.length > 2) {
        return true
      }
      return false
    }
  },
  modules: {},
  // plugins: [createPersistedState()]
  plugins: [createPersistedState({storage: {
    getItem: (key) => {
      const tmpStr = localStorage.getItem(key)
      if (tmpStr == null || tmpStr === undefined || tmpStr.length <= 0) {
        return {}
      }
      return aesDecrypt(tmpStr)
    },
    setItem: (key, value) => {
      if (value == null || value === undefined) {
        return
      }

      const tmpStr = aesEncrypt(value)
      localStorage.setItem(key, tmpStr)
    },
    removeItem: (key) => {
      localStorage.removeItem(key)
    }
  }})]
})
